/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package be.darling.scrt.generator;

import be.darling.scrt.data.Condition;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author jingle
 */
public class CRDesign extends Generator {

    public CRDesign()
    {
        super();
    }

    @Override
    public void setFirst(List<Condition> first)
    {
        Collections.sort(first);
        super.setFirst(first);
        System.out.println("Basic Randomization "+first);
    }

    @Override
    public List<Condition> generate(long nr, List<Condition> previous) {
        if (isComplete()){
            return generateNext(nr, previous);
        } else {
            return generateRandom();
        }
    }

    private List<Condition> generateNext(long nr, List<Condition> previous)
    {
        //http://www.perlmonks.org/?node_id=29374
        // http://www.thescripts.com/forum/thread629830.html
        // start with sorted list
        if (previous == null){
            return getBaseList();
        }

        int breakpoint = -1;
        for (int i=previous.size()-2; i>=0 ; i--){
            if (previous.get(i).compareTo(previous.get(i+1)) < 0 ){
                breakpoint = i ;
                //System.out.println("Breakpoint "+i);
                break;
            }
        }
        if (breakpoint < 0) return null; // stop

        int swapItem = 0;
        for (int i =previous.size()-1; i>breakpoint; i--){
            if (previous.get(breakpoint).compareTo(previous.get(i)) < 0 ){
                swapItem = i;
                break;
            }
        }

        // swap
        //System.out.println("swap "+breakpoint+" "+swapItem);
        Condition temp = previous.get(swapItem);
        previous.set(swapItem,previous.get(breakpoint));
        previous.set(breakpoint,temp);

        if (breakpoint < previous.size() -2){
            List sublist = previous.subList(breakpoint +1 , previous.size());
            Collections.reverse(sublist);// ,  Collections.reverseOrder());
        }


        return previous;
    }

    private List<Condition> generateRandom() {
        List<Condition> l = getBaseList();
        Collections.shuffle(l);
        return l;
    }



}
